import re

from django.conf import settings
from django.contrib.auth.backends import ModelBackend
from itsdangerous import TimedJSONWebSignatureSerializer as TJSSerializer

from users.models import User


def jwt_response_payload_handler(token,user=None,request=None):
    """重写此方法补充返回登录后的响应数据"""
    print('xxxx')
    return {
        'token':token,
        'user_id':user.id,
        'username':user.username
    }

def get_user_by_account(account):
    """

    :param account: 此参数有可能是username 有可能是mobile
    :return: 查到用户就返回user 否则返回None
    我的用户名是其他用户的手机号
    """
    try:
        if re.match(r'1[3-9]\d{9}',account):
            user = User.objects.get(mobile = account)
        else:
            user = User.objects.get(username = account)
    except User.DoesNotExist:
        return None
    else:
        return user  # 不要写User模型类名

class UsernameMobileAuthBackend(ModelBackend):
    """给django认证后端类定义子类，改写查询user逻辑，实现多账号登录"""

    def authenticate(self, request, username=None, password=None, **kwargs):
        # 根据前川传入的account 动态查询user
        user = get_user_by_account(username)
        # 校验密码是否正确
        if user and user.check_password(password):
            return user



def generate_email_verify_url(user):
    """生成邮箱激活url"""
    serializer = TJSSerializer(settings.SECRET_KEY, 24 * 60 * 60)

    data = {'user_id': user.id, 'email': user.email}

    token = serializer.dumps(data).decode()
    # 返回激活url
    return "http://www.meiduo.site:8080/success_verify_email.html?token=%s" % token